from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from clazz.models import Clazz
from rest_framework import serializers


class ClazzModelSerializer(serializers.ModelSerializer):
    # 添加可读字段
    department_name = serializers.CharField(source='department.name', read_only=True)
    
    class Meta:
        model = Clazz
        fields = ['id', 'name', 'code', 'department', 'department_name', 'created_at']


class ClazzViewSet(ModelViewSet):
    queryset = Clazz.objects.all()
    serializer_class = ClazzModelSerializer
    
    def list(self, request, *args, **kwargs):
        """获取全部班级列表"""
        response = super().list(request, *args, **kwargs)
        
        # 获取总班级数量
        total_count = self.queryset.count()
        
        res = {
            'status': 200,
            'data': {
                'info': response.data,
                'message': '班级列表获取成功',
                'total': total_count
            }
        }
        return Response(res, status=status.HTTP_200_OK)
    
    def retrieve(self, request, *args, **kwargs):
        """获取单个班级详情（包含学生信息）"""
        # 先获取班级基本信息
        response = super().retrieve(request, *args, **kwargs)
        
        # 获取当前班级对象
        clazz = self.get_object()
        
        # 获取该班级的所有学生
        from student.models import Student
        students = Student.objects.filter(clazz=clazz)
        
        # 序列化学生数据
        from student.views import StudentModelSerializer
        student_serializer = StudentModelSerializer(students, many=True)
        
        # 构建完整响应
        res = {
            'status': 200,
            'data': {
                'info': response.data,
                'message': '班级详情获取成功',
                'total': students.count(),
                'students': student_serializer.data,
            }
        }
        return Response(res, status=status.HTTP_200_OK)
    
    def create(self, request, *args, **kwargs):
        """创建班级"""
        response = super().create(request, *args, **kwargs)
        res = {
            'status': 200,
            'data': {
                'info': response.data,
                'message': '班级创建成功'
            }
        }
        return Response(res, status=status.HTTP_200_OK)
    
    def update(self, request, *args, **kwargs):
        """更新班级信息"""
        response = super().update(request, *args, **kwargs)
        res = {
            'status': 200,
            'data': {
                'info': response.data,
                'message': '班级更新成功'
            }
        }
        return Response(res, status=status.HTTP_200_OK)
    
    def destroy(self, request, *args, **kwargs):
        """删除班级"""
        try:
            response = super().destroy(request, *args, **kwargs)
            res = {
                'status': 200,
                'data': {
                    'info': {},
                    'message': '班级删除成功'
                }
            }
            return Response(res, status=status.HTTP_200_OK)
        except Exception as e:
            res = {
                'status': 404,
                'data': {
                    'info': {},
                    'message': '班级未找到'
                }
            }
            return Response(res, status=status.HTTP_404_NOT_FOUND)
    
    # 自定义action：按系部筛选班级
    @action(detail=False, methods=['get'])
    def by_department(self, request):
        """根据系部ID获取班级列表"""
        department_id = request.query_params.get('department_id')
        if department_id:
            classes = self.queryset.filter(department_id=department_id)
        else:
            classes = self.queryset
        
        serializer = self.get_serializer(classes, many=True)
        res = {
            'status': 200,
            'data': {
                'info': serializer.data,
                'message': '按系部筛选班级成功'
            }
        }
        return Response(res, status=status.HTTP_200_OK)
    
    # 自定义action：获取班级统计信息
    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取班级统计信息"""
        total_count = self.queryset.count()
        department_stats = []
        
        # 按系部分组统计
        from department.models import Department
        for dept in Department.objects.all():
            class_count = self.queryset.filter(department=dept).count()
            department_stats.append({
                'department_name': dept.name,
                'department_id': dept.id,
                'class_count': class_count
            })
        
        res = {
            'status': 200,
            'data': {
                'info': {
                    'total_count': total_count,
                    'department_stats': department_stats
                },
                'message': '班级统计信息获取成功'
            }
        }
        return Response(res, status=status.HTTP_200_OK)
